# -*- coding: utf-8 -*-
# @CreateTime: 2022/6/22 12:30
# @Author    : FangNan
# @File      : oss_helper.py
# @Software  : PyCharm
# 做一个有趣的人Write_By_FangNan
import hashlib
import oss2
import os

from oss2 import content_type_by_name


def percentage(consumed_bytes, total_bytes):
    if total_bytes:
        rate = int(100 * (float(consumed_bytes) / float(total_bytes)))
        print('\r{0}% '.format(rate), end='')


bucket = None


def getMd5(file):
    m0 = hashlib.md5()
    m0.update(file)
    return m0.hexdigest()


def upload_file_to_oss2(filename, bfile, content_type, is_md5_name=True):
    global bucket
    access_key_id = os.getenv('OSS_TEST_ACCESS_KEY_ID', 'LTAI5tHaJnojuufRPEhbyKex')
    access_key_secret = os.getenv('OSS_TEST_ACCESS_KEY_SECRET', '7tRr5rTtvdnR7Dzcbp9ojB5lvwddCP')
    bucket_name = os.getenv('OSS_TEST_BUCKET', 'xbweb3-new')
    endpoint = os.getenv('OSS_TEST_ENDPOINT', 'oss-ap-southeast-1.aliyuncs.com')
    # 确认上面的参数都填写正确了
    for param in (access_key_id, access_key_secret, bucket_name, endpoint):
        assert '<' not in param, '请设置参数：' + param
    if '.' in filename:
        filename_type = "." + filename.split(".")[-1]
    else:
        filename_type = ""
    if is_md5_name:
        filename = getMd5(bfile) + filename_type

    key = f'web3/{filename}'

    if bucket is None:
        bucket = oss2.Bucket(oss2.Auth(access_key_id, access_key_secret), endpoint, bucket_name)
    if content_type:
        headers = {"Content-Type": content_type}
    else:
        # 根据名字获取文件系统的content_type
        headers = {"Content-Type": content_type_by_name(filename)}
    res = bucket.put_object(key, bfile, progress_callback=percentage, headers=headers)

    if res.status == 200:
        new_url = f"https://{bucket_name}.{endpoint}/{key}"
        if 'https://xbweb3-new.oss-ap-southeast-1.aliyuncs.com/' in new_url:
            return f"https://images.3games.io/{key}"
        else:
            return new_url

    else:
        return False


if __name__ == '__main__':
    # 本地上传文件夹
    import os

    # for home, dirs, files in os.walk("/Users/atom/Desktop/csgo-9-6"):
    #     files.sort()
    #     for filename in files:
    #         fullname = os.path.join(home, filename)
    #         # print(fullname)
    #         with open(fullname, 'rb') as f:
    #             path = upload_file_to_oss2(filename, f.read(), None)
    #             print(filename, path)

    filename = "/Users/atom/Desktop/合成精灵图片（色相）/2+2+5+4+_3.png"
    with open(filename, 'rb') as f:
        path = upload_file_to_oss2(filename.split("/")[-1], f.read(), None, is_md5_name=True)
        print(filename, path)
